<?php
namespace Api\Service;

/**
 * 商品
 */
class GoodsService
{
    // 商品轮播图最大数量
    const BANNER_LIMIT = 10;
    // 商品分页大小
    const PAGET_NUMBER = 2;
    /**
     * 商品
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function find($goods_id)
    {
        $goods = M('goods')
            ->field('id,shop_id')
            ->where([
                'id' => $goods_id,
            ])->find();

        return $goods;
    }

    /**
     * 查找商品
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function search($data)
    {
        $where = [
            'is_delete' => 0,
        ];

        // 模糊查询
        if (isset($data['keyword']) && $data['keyword']) {
            $where['title|description'] = ['like', '%' . $data['keyword'] . '%'];
        }

        // 分类查找
        if (isset($data['category_id']) && $data['category_id']) {
            $where['category_id'] = $data['category_id'];
        }

        // 排序
        if (!isset($data['sort'])) {
            return [];
        }
        switch ($data['sort']) {
            case 'price':
                $order = 'price ' . $data['order'];
                break;
            case 'sales':
                $order = 'price ' . $data['order'];
                break;
            case 'new':
                $order = 'add_time ' . $data['order'];
                break;
            case 'default':
                $order = 'system_sort ' . $data['order'];
                break;
        }

        $count = $this->getGoodsCountByConditon($where);
        if ($count) {
            $page  = ceil($count / self::PAGET_NUMBER);
            $goods = M('goods')->alias('g')
                ->field('g.id,g.title,g.image,g.description,g.detail,g.price,g.market_price,g.collect,g.stock, (g.sales + g.virtual_sales) sales,s.id shop_id,s.name shop_name,s.logo shop_logo')
                ->join('__SHOP__ s on g.shop_id = s.id and s.is_open = 1')
                ->where($where)
                ->order($order)
                ->page(intval($data['page']), self::PAGET_NUMBER)
                ->select();
        }

        return [
            'count'    => intval($count),
            'cur_page' => intval($data['page']),
            'page'     => $page ? $page : 0,
            'data'     => $goods ? $goods : [],
        ];
    }

    /**
     * [getGoodsByConditon description]
     * @param  [type] $where [description]
     * @return [type]        [description]
     */
    public function getGoodsCountByConditon($where)
    {
        $count = M('goods')
            ->where($where)
            ->count();
        return intval($count);
    }

    /**
     * 商品
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function detail($goods_id)
    {
        $goods = S('goods_' . $goods_id);
        if (!$goods || true) {
            $goods = M('goods')->alias('g')
                ->field('g.id,g.title,g.image,g.description,g.detail,g.price,g.market_price,g.collect,g.stock, (g.sales + g.virtual_sales) sales,g.place,g.express_fee,s.id shop_id,s.name shop_name')
                ->join('__SHOP__ s on g.shop_id = s.id and s.is_open = 1')
                ->where([
                    'g.id'        => $goods_id,
                    'g.is_delete' => 0,
                    'g.is_sales'  => 1,
                ])->find();
            if ($goods) {
                // 商品轮播图
                $goods['banner'] = array_merge([$goods['image']], D('Api/Goods', 'Service')->banner($goods['id']));

                // 详情页面图片
                $goods['detail'] = D('Api/Goods', 'Service')->detailImage($goods['id']);

                // 评论
                $goods['review'] = D('Api/Review', 'Service')->goods($goods['id']);

                // 店铺
                $goods['shop'] = D('Api/Shop', 'Service')->info($goods['shop_id']);

                // 推荐商品/关联商品
                $goods['recommend'] = D('Api/Goods', 'Service')->recommend($goods['id']);
            }

            S('goods_' . $goods_id, $goods, setting('goods_cache_expire'));
        }

        return $goods ? $goods : [];
    }

    /**
     * 获取商品属性规格
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function specItem($goods_id)
    {
        $specs = M('goods_spec')
            ->where([
                'goods_id'  => $goods_id,
                'is_delete' => 0,
            ])->order('sort desc, id desc')
            ->getField('id,id,name', true);

        if (count($specs)) {
            $items = M('goods_item')
                ->where([
                    'goods_id'  => $goods_id,
                    'is_delete' => 0,
                ])->order('sort desc, id asc')
                ->getField('id,name,spec_id', true);
            if (count($items)) {
                foreach ($items as $key => $item) {
                    $specs[$item['spec_id']]['item'][] = $item;
                }
            }
        }

        $spec_item = M('goods_spec_item')
            ->field('id,item_ids,name,sales,price,market_price,stock,express_fee')
            ->where([
                'goods_id' => $goods_id,
                'is_sales' => 1,
            ])->order('id desc')
            ->select();

        return [
            'spec'      => $specs ? array_values($specs) : [],
            'spec_item' => $spec_item ? $spec_item : [],
        ];
    }

    /**
     * 获取新品（添加的算新品，更新不算新品）
     * @param  [type] $shop_id [description]
     * @return [type]          [description]
     */
    public function getNewByShopId($shop_id)
    {   
        $goods = S('shop_new_goods_' . $shop_id);
        if (!$goods || true) {
            $goods = M('goods')->field('id,shop_id,category_id,title,image,description,price,market_price,collect,(sales + virtual_sales) sales,stock,express_fee')
                ->where([
                    'shop_id'   => $shop_id,
                    'is_delete' => 0,
                ])->order('id desc')
                ->limit(setting('shop_new_goods_limit'))
                ->select();

            S('shop_new_goods_' . $shop_id, $goods, setting('shop_new_goods_expire'));
        }

        return $goods ? $goods : [];
    }

    /**
     * 获取新品数量
     * @param  [type] $shop_id [description]
     * @return [type]          [description]
     */
    public function getNewCountByShopId($shop_id)
    {
        return count($this->getNewByShopId($shop_id));
    }

    /**
     * 获取店铺默认列表商品，默认限制10个
     * @param  [type]  $shop_id [description]
     * @param  integer $limit     [description]
     * @return [type]           [description]
     */
    public function getGoods($shop_id, $limit = 10)
    {
        $goods = S('shop_default_goods_' . $shop_id);
        if (!$goods) {
            $goods = M('goods')
                ->field('id,shop_id,title,image,description,price,market_price,collect,(sales + virtual_sales) sales,stock')
                ->where([
                    'shop_id'   => $shop_id,
                    'is_delete' => 0,
                ])->order('is_recommend desc, id desc')
                ->limit($limit)
                ->select();

            S('shop_default_goods_' . $shop_id, $goods);
        }

        return $goods ? $goods : [];
    }

    /**
     * 商品关联其他的商品
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function recommend($goods_id)
    {
        $goods = M('goods_recommend')
            ->alias('r')
            ->field('g.id,g.title,g.image,g.price,g.market_price,g.collect,(g.sales + g.virtual_sales) sales,g.stock')
            ->join('__GOODS__ g on r.refer_id = g.id and r.is_delete = 0')
            ->where([
                'r.goods_id' => $goods_id,
            ])->order('sort desc, id desc')
            ->select();
        return $goods ? $goods : [];
    }

    /**
     * 商品轮播图
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function banner($goods_id)
    {
        $image = M('goods_banner')
            ->where([
                'goods_id'  => $goods_id,
                'is_delete' => 0,
            ])->limit(self::BANNER_LIMIT)
            ->order('sort desc, id asc')
            ->getField('image', true);
        return $image ? $image : [];
    }

    /**
     * 商品详情图
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function detailImage($goods_id)
    {
        $image = M('goods_detail')
            ->where([
                'goods_id'  => $goods_id,
                'is_delete' => 0,
            ])->order('sort desc, id asc')
            ->getField('image', true);
        return $image ? $image : [];
    }

    /**
     * 添加商品浏览记录
     * @param [type] $goods_id [description]
     */
    public function addHistory($user_id, $goods_id, $ext = [])
    {
        $data = [
            'user_id'  => $user_id,
            'goods_id' => $goods_id,
            'ext'      => json_encode($ext),
            'add_time' => CUR_DATETIME,
        ];
        M('goods_history')->add($data);
    }

    /**
     * 商品浏览记录
     * @return [type] [description]
     */
    public function history($user_id)
    {
        $goods = M('goods_history')
            ->alias('h')
            ->field('g.id,g.title,g.image,g.price,g.market_price,g.collect,(g.sales + g.virtual_sales) sales,g.stock')
            ->join('__GOODS__ g on h.goods_id = g.id')
            ->where([
                'h.user_id' => $user_id,
            ])->order('id desc')
            ->group('goods_id')
            ->select();

        return $goods ? $goods : [];
    }

    /**
     * 获取规格属性
     * @param  [type] $spec_item_id [description]
     * @return [type]               [description]
     */
    public function getSpecItem($spec_item_id)
    {
        $spec_item = S('spec_item_' . $spec_item_id);
        if (!$spec_item || true) {
            $items = M('goods_spec_item')
                ->where(['id' => $spec_item_id])
                ->getField('item_ids');
            $spec_item = M('goods_item')
                ->alias('i')
                ->field('s.name spec,i.name item')
                ->join('__GOODS_SPEC__ s on i.spec_id = s.id')
                ->where(['i.id' => ['in', explode(',', $items)]])
                ->select();
            S('spec_item_' . $spec_item_id, $spec_item);
        }
        return $spec_item;
    }

    /**
     * 规格属性字符串
     * @param string $value [description]
     */
    public function getSpecItemStr($spec_item_id)
    {
        $spec_items = $this->getSpecItem($spec_item_id);

        $text = '';
        foreach ($spec_items as $spec_item) {
            $text .= $spec_item['spec'] . ':' . $spec_item['item'] . ' ';
        }

        $text = substr($text, 0, -1);
        return $text ? $text : '';
    }

    /**
     * 获取门店商品
     * @param  [type] $shop_id [description]
     * @return [type]          [description]
     */
    public function shopGoods($shop_id, $cur_page)
    {
        $where = [
            'shop_id'   => $shop_id,
            'is_delete' => 0,
        ];

        $count = M('goods')->where($where)->count();
        if ($count) {
            $page  = ceil($count / self::PAGET_NUMBER);
            $goods = M('goods')
                ->field('id,image,price,market_price,collect,(sales + virtual_sales) sales,stock')
                ->where($where)
                ->order('is_recommend desc,id desc')
                ->page($cur_page, self::PAGET_NUMBER)
                ->select();
        }

        return [
            'count'    => intval($count),
            'cur_page' => intval($cur_page),
            'page'     => $page ? $page : 0,
            'data'     => $goods ? $goods : [],
        ];
    }
}
